package com.jsu.clubmanagementsystem.service.review.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jsu.clubmanagementsystem.common.ErrorCode;
import com.jsu.clubmanagementsystem.exception.BusinessException;
import com.jsu.clubmanagementsystem.model.dto.activityapplication.ActivityApplicationAdditionalInfo;
import com.jsu.clubmanagementsystem.model.dto.club.ClubAddRequest;
import com.jsu.clubmanagementsystem.model.dto.club.ClubUpdateRequest;
import com.jsu.clubmanagementsystem.model.entity.*;
import com.jsu.clubmanagementsystem.model.enums.ApplicationTypeEnum;
import com.jsu.clubmanagementsystem.model.enums.ClubMemberRoleEnum;
import com.jsu.clubmanagementsystem.model.enums.ReviewResultEnum;
import com.jsu.clubmanagementsystem.service.activity.ActivityService;
import com.jsu.clubmanagementsystem.service.application.ActivityApplicationService;
import com.jsu.clubmanagementsystem.service.application.ClubApplicationService;
import com.jsu.clubmanagementsystem.service.application.UserApplicationService;
import com.jsu.clubmanagementsystem.service.club.ClubService;
import com.jsu.clubmanagementsystem.service.user.UserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class AcceptedReviewProcessor {

    @Resource
    private UserService userService;

    @Resource
    private ClubService clubService;

    @Resource
    private ActivityService activityService;

    @Resource
    private UserApplicationService userApplicationService;

    @Resource
    private ClubApplicationService clubApplicationService;

    @Resource
    private ActivityApplicationService activityApplicationService;

    /**
     * 审核账号注销申请
     *
     * @param application
     * @return
     */
    public void doDeleteUserApplicationReview(UserApplication application) {
        Long userId = application.getUserId();
        // 删除用户所有未被审核的申请
        QueryWrapper<UserApplication> userApplicationQueryWrapper = new QueryWrapper<>();
        userApplicationQueryWrapper.eq("userId", userId);
        userApplicationQueryWrapper.ne("type", ApplicationTypeEnum.DELETE_USER.getCode());
        userApplicationQueryWrapper.eq("result", ReviewResultEnum.WAITING.getCode());
        if (userApplicationService.count(userApplicationQueryWrapper) > 0 &&
                !userApplicationService.remove(userApplicationQueryWrapper)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除用户未被审核的申请失败");
        }
        QueryWrapper<ClubApplication> clubApplicationQueryWrapper = new QueryWrapper<>();
        clubApplicationQueryWrapper.eq("userId", userId);
        clubApplicationQueryWrapper.eq("result", ReviewResultEnum.WAITING.getCode());
        if (clubApplicationService.count(clubApplicationQueryWrapper) > 0 &&
                !clubApplicationService.remove(clubApplicationQueryWrapper)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除用户未审核申请失败");
        }
        QueryWrapper<ActivityApplication> activityApplicationQueryWrapper = new QueryWrapper<>();
        activityApplicationQueryWrapper.eq("userId", userId);
        activityApplicationQueryWrapper.eq("result", ReviewResultEnum.WAITING.getCode());
        if (activityApplicationService.count(activityApplicationQueryWrapper) > 0 &&
                !activityApplicationService.remove(activityApplicationQueryWrapper)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除用户未审核申请失败");
        }

        // 软删除
        if (!userService.removeById(userId)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除用户失败");
        }
    }

    /**
     * 审核加入社团申请
     *
     * @param application
     * @return
     */
    public void doJoinClubApplicationReview(UserApplication application) {
        ClubMembership membership = new ClubMembership();
        membership.setUserId(application.getUserId());
        membership.setClubId(application.getAdditionalInfo());
        membership.setIdentity(ClubMemberRoleEnum.MEMBER.getInfo());
        if (!clubService.addMemberToClub(membership)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "加入社团失败");
        }
    }

    /**
     * 审核退出社团申请
     *
     * @param application
     * @return
     */
    public void doQuitClubApplicationReview(UserApplication application) {
        Long userId = application.getUserId();
        Long clubId = application.getAdditionalInfo();

        // 删除用户所提交的未被审核的 参加该社团的活动的申请
        QueryWrapper<UserApplication> userJoinApplicationQueryWrapper = new QueryWrapper<>();
        userJoinApplicationQueryWrapper.eq("type", ApplicationTypeEnum.ENGAGE_ACTIVITY.getCode());
        userJoinApplicationQueryWrapper.eq("result", ReviewResultEnum.WAITING.getCode());
        userJoinApplicationQueryWrapper.eq("userId", userId);
        if (userApplicationService.count(userJoinApplicationQueryWrapper) > 0 &&
                !userApplicationService.remove(userJoinApplicationQueryWrapper)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除用户未被审核的参与活动申请失败");
        }

        //删除成员
        ClubMembership membership = new ClubMembership();
        membership.setUserId(userId);
        membership.setClubId(clubId);
        if (!clubService.deleteMemberFromClub(membership, false)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除成员失败");
        }
    }

    /**
     * 审核参加活动申请
     *
     * @param application
     * @return
     */
    public void doEngageActivityApplicationReview(UserApplication application) {
        ActivityMembership membership = new ActivityMembership();
        membership.setUserId(application.getUserId());
        membership.setActivityId(application.getAdditionalInfo());
        if (!activityService.addMemberToActivity(membership)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "添加活动成员失败");
        }
    }

    /**
     * 审核退出活动申请
     *
     * @param application
     * @return
     */
    public void doQuitActivityApplicationReview(UserApplication application) {
        ActivityMembership membership = new ActivityMembership();
        membership.setUserId(application.getUserId());
        membership.setActivityId(application.getAdditionalInfo());
        if (!activityService.deleteMemberFromActivity(membership)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除活动成员失败");
        }
    }

    /**
     * 审核创建社团申请
     *
     * @param application
     * @return
     */
    public void doCreateClubApplicationReview(ClubApplication application) {
        ClubAddRequest addRequest = new ClubAddRequest();
        addRequest.setUserId(application.getUserId());
        addRequest.setClubName(application.getClubName());
        addRequest.setIntroduction(application.getClubIntroduction());
        addRequest.setTags(JSONUtil.toList(application.getClubTags(), String.class));

        long clubId = clubService.addClub(addRequest);
        application.setClubId(clubId);
        if (!clubApplicationService.updateById(application)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "插入成功后更新申请信息失败");
        }
    }

    /**
     * 审核注销社团申请
     *
     * @param application
     * @return
     */
    public void doDeleteClubApplicationReview(ClubApplication application) {
        Long clubId = application.getClubId();
        Club club = clubService.getById(clubId);

        //删除所提交的未审核申请: 修改社团信息、举办活动、取消活动、修改活动信息
        if (!this.deleteClubApplicationForDeleteClub(club)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除相关未审核申请失败");
        }
        if (!this.deleteActivityApplicationForDeleteClub(club)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除相关未审核申请失败");
        }
        //删除社团
        if (!clubService.deleteClub1(club)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除社团失败");
        }
    }

    /**
     * 审核修改社团信息申请
     *
     * @param application
     * @return
     */
    public void doUpdateClubApplicationReview(ClubApplication application) {
        ClubUpdateRequest updateRequest = new ClubUpdateRequest();
        updateRequest.setId(application.getClubId());
        updateRequest.setUserId(application.getNewManagerId());
        updateRequest.setClubName(application.getClubName());
        updateRequest.setIntroduction(application.getClubIntroduction());

        String clubTags = application.getClubTags();
        updateRequest.setTags(JSONUtil.toList(clubTags, String.class));
        if (!clubService.updateClub(updateRequest)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更新社团信息失败");
        }
    }

    /**
     * 审核举办活动申请
     *
     * @param application
     * @return
     */
    public void doCreateActivityApplicationReview(ActivityApplication application) {
        String additionalInfo = application.getAdditionalInfo();
        ActivityApplicationAdditionalInfo applicationAdditionalInfo = JSONUtil.toBean(additionalInfo, ActivityApplicationAdditionalInfo.class);
        Activity activity = new Activity();
        activity.setClubId(application.getTargetId());
        activity.setStartTime(application.getStartTime());
        activity.setEndTime(application.getEndTime());
        activity.setActivityName(applicationAdditionalInfo.getActivityName());
        activity.setActivityTitle(applicationAdditionalInfo.getActivityTitle());
        activity.setActivityContent(applicationAdditionalInfo.getActivityContent());

        activityService.addActivity(activity);
    }

    /**
     * 审核取消活动申请
     *
     * @param application
     * @return
     */
    public void doDeleteActivityApplicationReview(ActivityApplication application) {
        Long activityId = application.getTargetId();
        QueryWrapper<ActivityApplication> activityApplicationQueryWrapper = new QueryWrapper<>();
        activityApplicationQueryWrapper.eq("type", ApplicationTypeEnum.CHANGE_ACTIVITY_INFO.getCode());
        activityApplicationQueryWrapper.eq("targetId", activityId);
        if (activityApplicationService.count(activityApplicationQueryWrapper) > 0 &&
                !activityApplicationService.remove(activityApplicationQueryWrapper)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除活动未被审核的修改信息申请失败");
        }

        Activity activity = activityService.getById(activityId);
        activityService.deleteActivity(activity);
    }

    /**
     * 审核修改活动信息申请 （活动需要是 已确定举办未开始 状态）
     *
     * @param application
     * @return
     */
    public void doUpdateActivityApplicationReview(ActivityApplication application) {
        String additionalInfo = application.getAdditionalInfo();
        ActivityApplicationAdditionalInfo applicationAdditionalInfo = JSONUtil.toBean(additionalInfo, ActivityApplicationAdditionalInfo.class);

        Activity activity = new Activity();
        activity.setId(application.getTargetId());
        activity.setStartTime(application.getStartTime());
        activity.setEndTime(application.getEndTime());
        activity.setActivityName(applicationAdditionalInfo.getActivityName());
        activity.setActivityTitle(applicationAdditionalInfo.getActivityTitle());
        activity.setActivityContent(applicationAdditionalInfo.getActivityContent());

        if (!activityService.updateActivity(activity)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更新活动信息失败");
        }
    }

    /**
     * 为删除社团设置的删除ClubApplication功能，当社团删除时删除其未被审核的修改社团信息申请
     *
     * @param club
     * @return
     */
    public boolean deleteClubApplicationForDeleteClub(Club club) {
        Long clubId = club.getId();
        QueryWrapper<ClubApplication> clubApplicationQueryWrapper = new QueryWrapper<>();
        clubApplicationQueryWrapper.eq("type", ApplicationTypeEnum.CHANGE_CLUB_INFO.getCode());
        clubApplicationQueryWrapper.eq("result", ReviewResultEnum.WAITING.getCode());
        clubApplicationQueryWrapper.eq("clubId", clubId);
        if (clubApplicationService.count(clubApplicationQueryWrapper) > 0 &&
                !clubApplicationService.remove(clubApplicationQueryWrapper)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除相关未审核申请失败");
        }
        return true;
    }

    /**
     * 为删除社团设置的删除申请功能
     *
     * @param club
     * @return
     */
    public boolean deleteActivityApplicationForDeleteClub(Club club) {
        Long clubId = club.getId();
        List<Long> deleteActivityApplicationIdList = null;

        QueryWrapper<ActivityApplication> queryWrapperOfCreateActivityApplication = new QueryWrapper<>();
        queryWrapperOfCreateActivityApplication.eq("type", ApplicationTypeEnum.CREATE_ACTIVITY.getCode());
        queryWrapperOfCreateActivityApplication.eq("result", ReviewResultEnum.WAITING.getCode());
        queryWrapperOfCreateActivityApplication.eq("targetId", clubId);
        deleteActivityApplicationIdList = activityApplicationService.list(queryWrapperOfCreateActivityApplication).stream()
                .map(ActivityApplication::getId)
                .collect(Collectors.toList());

        List<Long> activityIdListOfClub = activityService.getActivityListOfClub(clubId).stream()
                .map(Activity::getId)
                .collect(Collectors.toList());
        QueryWrapper<ActivityApplication> queryWrapperOfChangeActivityInfoApplication = new QueryWrapper<>();
        if (!activityIdListOfClub.isEmpty()) {
            queryWrapperOfChangeActivityInfoApplication.in("type", ApplicationTypeEnum.CHANGE_ACTIVITY_INFO.getCode());
            queryWrapperOfChangeActivityInfoApplication.eq("result", ReviewResultEnum.WAITING.getCode());
            queryWrapperOfChangeActivityInfoApplication.in("targetId", activityIdListOfClub);
            deleteActivityApplicationIdList.addAll(activityApplicationService.list(queryWrapperOfChangeActivityInfoApplication).stream()
                    .map(ActivityApplication::getId)
                    .collect(Collectors.toList()));
        }

        if (!deleteActivityApplicationIdList.isEmpty() &&
                !activityApplicationService.removeBatchByIds(deleteActivityApplicationIdList)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除相关未审核申请失败");
        }
        return true;
    }
}
